package com.ef.web.action;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.ServletActionContext;
import org.hibernate.Criteria;
import org.hibernate.criterion.MatchMode;

import com.ef.constant.EClassType;
import com.ef.constant.ELeadsClassStatus;
import com.ef.constant.ETimeline;
import com.ef.domain.ClassEntity;
import com.ef.domain.ClassFocus;
import com.ef.domain.ClassType;
import com.ef.domain.Classroom;
import com.ef.domain.LeadsClassEntity;
import com.ef.domain.Teacher;
import com.ef.service.ClassArrangeService;
import com.ef.service.ClassFocusService;
import com.ef.service.ClassTypeService;
import com.ef.service.ClassroomService;
import com.ef.service.LeadsClassEntityService;
import com.ef.service.TeacherService;
import com.ef.util.CalendarUtil;
import com.ef.util.CustomExample;

/**
 * 排课. <br/>
 * 
 * @author CYG create:2009-12-13 上午09:06:34
 */
public class ClassArrangeAction extends BaseAction<ClassEntity> {

	private static final long serialVersionUID = 2008996134431247542L;

	private ClassArrangeService classArrangeService;

	private LeadsClassEntityService leadsClassEntityService;

	private List<LeadsClassEntity> leadsClassEntityList;

	private TeacherService teacherService;

	private ClassTypeService classTypeService;

	private ClassFocusService classFocusService;

	private ClassroomService classroomService;

	private List<ClassType> classTypelist;

	private List<ClassFocus> classFocuslist;

	private List<Classroom> classroomlist;
	/**
	 * 当前排课的年份
	 */
	private int year;

	/**
	 * 当前排课的周
	 */
	private int week;

	private Date selDate;

	private String selTime;
	/**
	 * 这周的七天
	 */
	private List<Date> days;

	/**
	 *  
	 */
	private List<Date> normalDays;

	/**
	 *  
	 */
	private List<Date> weekendDays;
	/**
	 * 所以参与排课的老师
	 */
	private List<Teacher> teachers;

	/**
	 * 时间轴
	 */
	private List<ETimeline> normalTimeline;

	/**
	 * 时间轴
	 */
	private List<ETimeline> weekendTimeline;

	public List<Date> getDays() {
		return days;
	}

	public void setDays(List<Date> days) {
		this.days = days;
	}

	public List<Teacher> getTeachers() {
		return teachers;
	}

	public void setTeachers(List<Teacher> teachers) {
		this.teachers = teachers;
	}

	public int getYear() {
		return year;
	}

	public void setYear(int year) {
		this.year = year;
	}

	public int getWeek() {
		return week;
	}

	public void setWeek(int week) {
		this.week = week;
	}

	/**
	 * 初始化到本周
	 */
	public ClassArrangeAction() {
		// 获取当前是某年某周
		// @NOTE 需要对year进行处理
		Calendar now = Calendar.getInstance();
		selDate = now.getTime();
		now.setFirstDayOfWeek(Calendar.MONDAY);
		int day = now.get(Calendar.DAY_OF_YEAR);
		week = now.get(Calendar.WEEK_OF_YEAR);
		year = now.get(Calendar.YEAR);
		if (day > 7 && week == 1) {
			year++;
		}
		week++;
		// //NOTE week要-1
		if (year == 2010) {
			week = week - 1;
		}
		normalTimeline = ETimeline.getNomarlTimeline();
		weekendTimeline = ETimeline.getWeekendTimeline();
	}

	public String view() {
		leadsClassEntityList = leadsClassEntityService
				.getLeadsClassEntityListWithClassEntity(this.getModel());
		return VIEW;
	}

	/**
	 * 根据条件课程。
	 * 
	 * @return
	 */
	@SuppressWarnings("serial")
	public String list() {
		ClassEntity smp = this.getModel();
		smp.setClassDate(selDate);
		if (selTime != null) {
			smp.setClassTime(ETimeline.messageOf(selTime));
		} else {
			smp.setClassTime(null);
		}
		this.listResult = classArrangeService.findByExample(
				new CustomExample<ClassEntity>(smp) {
					public void appendCondition(Criteria criteria) {
						this.excludeProperty("bookingCount");
						this.excludeProperty("allStudent");
						this.excludeProperty("checkedTimes");
						this.excludeProperty("type");
						this.enableLike(MatchMode.ANYWHERE);
					}
				}, this.getStartIndex(), this.getPageSize());
		return LIST;
	}

	public String selectClassTypeAjax() {
		HttpServletRequest request = ServletActionContext.getRequest();
		String typeid = request.getParameter("classtypeid");

		if (typeid != null && typeid.trim().length() > 0) {
			classFocuslist = classFocusService.findByType(Long.valueOf(typeid
					.trim()));
			ClassType type = classTypeService.findById(Long.valueOf(typeid
					.trim()));
			if (type != null) {
				if (type.getType().equals(EClassType.WK)) {
					if (getSessionUser().getSchool() != null) {
						classroomlist = classroomService
								.findByCapacityInSchool(getSessionUser()
										.getSchool().getId(), 25);
					} else {
						classroomlist = classroomService.findAllValid();
					}
				} else if (type.getType().equals(EClassType.LC)) {
					if (getSessionUser().getSchool() != null) {
						classroomlist = classroomService
								.findByCapacityInSchool(getSessionUser()
										.getSchool().getId(), 15);
					} else {
						classroomlist = classroomService.findAllValid();
					}
				} else if (type.getType().equals(EClassType.F2F)
						|| type.getType().equals(EClassType.INTERVIEW)) {
					if (getSessionUser().getSchool() != null) {
						classroomlist = classroomService
								.findByCapacityInSchool(getSessionUser()
										.getSchool().getId(), 4);
					} else {
						classroomlist = classroomService.findAllValid();
					}
				} else {
					if (getSessionUser().getSchool() != null) {
						classroomlist = classroomService
								.findAllValidInSchool(getSessionUser()
										.getSchool().getId());
					} else {
						classroomlist = classroomService.findAllValid();
					}
				}
			}
		} else {
			if (getSessionUser().getSchool() != null) {
				classroomlist = classroomService
						.findAllValidInSchool(getSessionUser().getSchool()
								.getId());
			} else {
				classroomlist = classroomService.findAllValid();
			}
			classFocuslist = classFocusService.findALLValid();
		}
		this.response(getSelectTypeResponse());
		return null;
	}

	public String beforeArrange() {
		teachers = teacherService.getAllValidTeachers();
		classTypelist = classTypeService.findALLValid();
		classroomlist = classroomService.findAllValid();
		classFocuslist = classFocusService.findALLValid();
		int trueWeek = week;
		if (year == 2010) {
			trueWeek = trueWeek + 1;
		}
		days = CalendarUtil.getWeekTimelineDaysWithMonDayIsFirstDay(year,
				trueWeek);
		return "beforeArrange";
	}

	public List<ETimeline> getTimeline(Date date) {
		if (CalendarUtil.isWeekend(date)) {
			return weekendTimeline;
		} else {
			return normalTimeline;
		}
	}

	/**
	 * 使用AJAX进行排课。
	 * 
	 * @return
	 */
	public String doArrange() {
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
		HttpServletRequest request = ServletActionContext.getRequest();
		String entityid = request.getParameter("entityid");
		String date = request.getParameter("date");
		String time = request.getParameter("time");
		String teacherid = request.getParameter("teacherid");
		String typeid = request.getParameter("classtypeid");
		String focusid = request.getParameter("classfocusid");
		String roomid = request.getParameter("classroomid");
		String topic = request.getParameter("topic");
		ClassEntity curEntity = null;
		try {
			if (entityid != null && entityid.trim().length() > 0) {
				curEntity = classArrangeService
						.findById(Long.valueOf(entityid));
			} else {
				curEntity = new ClassEntity();
			}
			if (roomid != null && roomid.trim().length() > 0) {// 判断是否有ROOM的冲突
//				ClassEntity jentity = getClassEntityByClassroom(date, time,
//						roomid);
				// if (jentity != null && !jentity.equals(curEntity)) { // 有冲突
				// String info = "At " + jentity.getClassDate() + " "
				// + jentity.getClassTime() + " teacher "
				// + jentity.getTeacher().getName() + " using room "
				// + jentity.getClassroom().getName();
				// return responseError(info);
				// }
				List<ClassEntity> clzs=classArrangeService.getClassEntityByDateTime(df.parse(date),
						ETimeline.messageOf(time.trim()));
				String info="Room Used In Same Time:";
				boolean used=false;
				for (ClassEntity clz:clzs){
					info=info+clz.getClassroom().getName()+";";
					 if (clz.getClassroom().getId().toString().equals(roomid)){
						 used=true;
					 }
				}
				if (used){
					return responseError(info);
				}
			}

			if (date != null && date.trim().length() > 0) {
				curEntity.setClassDate(df.parse(date.trim()));
			}
			if (time != null && time.trim().length() > 0) {
				curEntity.setClassTime(ETimeline.messageOf(time.trim()));
			}
			;
			if (teacherid != null && teacherid.trim().length() > 0) {
				curEntity.setTeacher(teacherService.findById(Long
						.valueOf(teacherid)));
			}
			if (typeid != null && typeid.trim().length() > 0) {
				curEntity.setClassType(classTypeService.findById(Long
						.valueOf(typeid)));
			}
			if (focusid != null && focusid.trim().length() > 0) {
				curEntity.setClassFocus(classFocusService.findById(Long
						.valueOf(focusid)));
			}
			if (roomid != null && roomid.trim().length() > 0) {
				curEntity.setClassroom(classroomService.findById(Long
						.valueOf(roomid)));
			}
			curEntity.setTopic(topic);
			classArrangeService.saveOrUpdate(curEntity);
			response(getEntityResponse(curEntity));
		} catch (Exception e) {
			return responseError(e.getMessage());
		}
		return null;
	}

	/**
	 * 使用AJAX取消排课。
	 * 
	 * @return
	 */
	public String deleteArrange() {
		HttpServletRequest request = ServletActionContext.getRequest();
		String entityid = request.getParameter("entityid");
		try {
			ClassEntity centity = classArrangeService.findById(Long
					.valueOf(entityid));
			List<LeadsClassEntity> classEntitys = leadsClassEntityService
					.getLeadsClassEntityListWithClassEntity(centity);
			for (LeadsClassEntity lc : classEntitys) {
				if (!lc.getClassStatus().equals(ELeadsClassStatus.CANCEL)) {
					return this
							.responseError("this class have somebody can't delete");
				}
			}
			classArrangeService.delete(centity);
			response("<entityid>-1</entityid><color>#FFFFFF</color><info></info>");
		} catch (Exception e) {
			return responseError(e.getMessage());
		}
		return null;
	}

	protected String getEntityResponse(ClassEntity curEntity) {
		String typeid = "";
		String type = "";
		String focusid = "";
		String focus = "";
		String roomid = "";
		String room = "";
		String topic = "";
		String msg = "";
		String entityid = "";
		String color = "";
		String msgall = "";
		if (curEntity != null) {
			if (curEntity.getClassType() != null) {
				typeid = curEntity.getClassType().getId().toString();
				type = curEntity.getClassType().getName();
			}
			if (curEntity.getClassFocus() != null) {
				focusid = curEntity.getClassFocus().getId().toString();
				focus = curEntity.getClassFocus().getName();
			}
			if (curEntity.getClassroom() != null) {
				roomid = curEntity.getClassroom().getId().toString();
				room = curEntity.getClassroom().getName();
			}
			if (curEntity.getTopic() != null) {
				topic = curEntity.getTopic();

			}

			entityid = curEntity.getId().toString();
			msg = curEntity.getArrangeMessage();
			msgall = msg;
			if (msg.length() > 10) {
				msg = msg.substring(0, 10);
			}
			color = curEntity.getArrangeColor();
		}
		return "<entityid>" + entityid + "</entityid>" + "<typeid>" + typeid
				+ "</typeid>" + "<type>" + type + "</type>" + "<focusid>"
				+ focusid + "</focusid>" + "<focus>" + focus + "</focus>"
				+ "<roomid>" + roomid + "</roomid>" + "<room>" + room
				+ "</room>" + "<color>" + color + "</color>"
				+ "<topic><![CDATA[" + topic + "]]></topic>"
				+ "<info><![CDATA[" + msg + "]]></info>" + "<infoall><![CDATA["
				+ msgall + "]]></infoall>";
	}

	protected String getSelectTypeResponse() {
		StringBuffer rsp = new StringBuffer();
		for (ClassFocus focus : classFocuslist) {
			String topic = focus.getDefaultTopic().replace("&", " ");
			rsp.append("<focus>").append("{id:").append(focus.getId()).append(
					",name:\"").append(focus.getName()).append("\",topic:\"")
					.append(topic).append("\"}").append("</focus>");
		}
		for (Classroom room : classroomlist) {
			rsp.append("<room>").append("{id:").append(room.getId()).append(
					",name:\"").append(room.getName()).append("\"}").append(
					"</room>");
		}
		return rsp.toString();
	}

	protected void initClassEntityByClassroom(Date date, ETimeline timeline,
			String classroomid) {
		try {
			entity = classArrangeService.getClassEntityByDateTimeAndClassroom(
					date, timeline, Long.valueOf(classroomid));
		} catch (Exception e) {
			// TODO: handle exception
		}
	}

	protected ClassEntity getClassEntityByClassroom(String date, String time,
			String roomid) throws Exception {
		try {
			SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
			return classArrangeService.getClassEntityByDateTimeAndClassroom(df
					.parse(date.trim()), ETimeline.messageOf(time.trim()), Long
					.valueOf(roomid));
		} catch (Exception e) {
			throw e;
		}
	}

	private HashMap<Long, HashMap<String, ClassEntity>> teacherClassMaps = null;

	public String getClassEntityId(Date date, ETimeline timeline,
			String teacherid) {
		if (teacherClassMaps == null) {
			teacherClassMaps = classArrangeService.getClassEntityMapInTime(
					CalendarUtil.getMondayOfWeekWithMonDayIsFirstDay(date),
					CalendarUtil.getSundayOfWeekWithMonDayIsFirstDay(date));
		}
		SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd");
		HashMap<String, ClassEntity> cMap = teacherClassMaps.get(Long
				.valueOf(teacherid));
		if (cMap == null) {
			return "-1";
		} else {
			ClassEntity entity = cMap.get(sd.format(date) + timeline.getName());
			if (entity != null) {
				return entity.getId().toString();
			} else {
				return "-1";
			}
		}
	};

	public String getClassEntityInfoAll(Date date, ETimeline timeline,
			String teacherid) {
		if (teacherClassMaps == null) {
			teacherClassMaps = classArrangeService.getClassEntityMapInTime(
					CalendarUtil.getMondayOfWeekWithMonDayIsFirstDay(date),
					CalendarUtil.getSundayOfWeekWithMonDayIsFirstDay(date));
		}
		SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd");
		HashMap<String, ClassEntity> cMap = teacherClassMaps.get(Long
				.valueOf(teacherid));
		if (cMap == null) {
			return "";
		} else {
			ClassEntity entity = cMap.get(sd.format(date) + timeline.getName());
			if (entity != null) {
				return entity.getArrangeMessage();
			} else {
				return "";
			}
		}
	}

	public String getClassEntityInfo(Date date, ETimeline timeline,
			String teacherid) {
		if (teacherClassMaps == null) {
			teacherClassMaps = classArrangeService.getClassEntityMapInTime(
					CalendarUtil.getMondayOfWeekWithMonDayIsFirstDay(date),
					CalendarUtil.getSundayOfWeekWithMonDayIsFirstDay(date));
		}
		SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd");
		HashMap<String, ClassEntity> cMap = teacherClassMaps.get(Long
				.valueOf(teacherid));
		if (cMap == null) {
			return "";
		} else {
			ClassEntity entity = cMap.get(sd.format(date) + timeline.getName());
			if (entity != null) {
				String msg = entity.getArrangeMessage();
				if (msg.length() > 11) {
					msg = msg.substring(0, 11);
				}
				return msg;
			} else {
				return "";
			}
		}
	}

	public String getClassEntityColor(Date date, ETimeline timeline,
			String teacherid) {
		if (teacherClassMaps == null) {
			teacherClassMaps = classArrangeService.getClassEntityMapInTime(
					CalendarUtil.getMondayOfWeekWithMonDayIsFirstDay(date),
					CalendarUtil.getSundayOfWeekWithMonDayIsFirstDay(date));
		}
		SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd");
		HashMap<String, ClassEntity> cMap = teacherClassMaps.get(Long
				.valueOf(teacherid));
		if (cMap == null) {
			return "#FFFFFF";
		} else {
			ClassEntity entity = cMap.get(sd.format(date) + timeline.getName());
			if (entity != null) {
				return entity.getArrangeColor();
			} else {
				return "#FFFFFF";
			}
		}
	}

	private Date olddate;

	private ETimeline oldtime;

	private String oldchoiceid;

	public String getClassEntityInfoByClassroom(Date date, ETimeline timeline,
			String classroomid) {
		if (!date.equals(olddate) || !timeline.equals(oldtime)
				|| !teacherid.equals(oldchoiceid)) {
			initClassEntityByClassroom(date, timeline, classroomid);
			olddate = date;
			oldtime = timeline;
			oldchoiceid = classroomid;
		}
		if (entity != null) {
			return entity.getMessage();
		} else {
			return "";
		}
	}

	/**
	 * 选到的老师
	 */
	private Long teacherid;

	private String teachername;

	public String teacherCalendar() {
		int trueWeek = week;
		if (year == 2010) {
			trueWeek = trueWeek + 1;
		}
		normalDays = CalendarUtil.getNormalDaysWithMonDayIsFirstDay(year,
				trueWeek);
		weekendDays = CalendarUtil.getWeekendDaysWithMonDayIsFirstDay(year,
				trueWeek);
		// System.out.println("teachers size:" + teachers.size());
		return "teacherCalendar";
	}

	/**
	 * 选到的教室
	 */
	private Long classroomid;

	/**
	 * 选到的教室
	 */
	private String classroomname;

	public String classroomCalendar() {
		int trueWeek = week;
		if (year == 2010) {
			trueWeek = trueWeek + 1;
		}
		normalDays = CalendarUtil.getNormalDaysWithMonDayIsFirstDay(year,
				trueWeek);
		weekendDays = CalendarUtil.getWeekendDaysWithMonDayIsFirstDay(year,
				trueWeek);
		return "classroomCalendar";
	}

	public ClassTypeService getClassTypeService() {
		return classTypeService;
	}

	public void setClassTypeService(ClassTypeService classTypeService) {
		this.classTypeService = classTypeService;
	}

	public ClassFocusService getClassFocusService() {
		return classFocusService;
	}

	public void setClassFocusService(ClassFocusService classFocusService) {
		this.classFocusService = classFocusService;
	}

	public ClassroomService getClassroomService() {
		return classroomService;
	}

	public void setClassroomService(ClassroomService classroomService) {
		this.classroomService = classroomService;
	}

	public TeacherService getTeacherService() {
		return teacherService;
	}

	public void setTeacherService(TeacherService teacherService) {
		this.teacherService = teacherService;
	}

	public ClassArrangeService getClassArrangeService() {
		return classArrangeService;
	}

	public void setClassArrangeService(ClassArrangeService classArrangeService) {
		this.classArrangeService = classArrangeService;
	}

	public Long getTeacherid() {
		return teacherid;
	}

	public void setTeacherid(Long teacherid) {
		this.teacherid = teacherid;
	}

	public Long getClassroomid() {
		return classroomid;
	}

	public void setClassroomid(Long classroomid) {
		this.classroomid = classroomid;
	}

	public String getTeachername() {
		return teachername;
	}

	public void setTeachername(String teachername) {
		this.teachername = teachername;
	}

	public String getClassroomname() {
		return classroomname;
	}

	public void setClassroomname(String classroomname) {
		this.classroomname = classroomname;
	}

	public Date getSelDate() {
		return selDate;
	}

	public void setSelDate(Date selDate) {
		this.selDate = selDate;
	}

	public String getSelTime() {
		return selTime;
	}

	public void setSelTime(String selTime) {
		this.selTime = selTime;
	}

	public LeadsClassEntityService getLeadsClassEntityService() {
		return leadsClassEntityService;
	}

	public void setLeadsClassEntityService(
			LeadsClassEntityService leadsClassEntityService) {
		this.leadsClassEntityService = leadsClassEntityService;
	}

	public List<LeadsClassEntity> getLeadsClassEntityList() {
		return leadsClassEntityList;
	}

	public void setLeadsClassEntityList(
			List<LeadsClassEntity> leadsClassEntityList) {
		this.leadsClassEntityList = leadsClassEntityList;
	}

	public List<ClassType> getClassTypelist() {
		return classTypelist;
	}

	public void setClassTypelist(List<ClassType> classTypelist) {
		this.classTypelist = classTypelist;
	}

	public List<ClassFocus> getClassFocuslist() {
		return classFocuslist;
	}

	public void setClassFocuslist(List<ClassFocus> classFocuslist) {
		this.classFocuslist = classFocuslist;
	}

	public List<Classroom> getClassroomlist() {
		return classroomlist;
	}

	public void setClassroomlist(List<Classroom> classroomlist) {
		this.classroomlist = classroomlist;
	}

	public List<ETimeline> getNormalTimeline() {
		return normalTimeline;
	}

	public void setNormalTimeline(List<ETimeline> normalTimeline) {
		this.normalTimeline = normalTimeline;
	}

	public List<ETimeline> getWeekendTimeline() {
		return weekendTimeline;
	}

	public void setWeekendTimeline(List<ETimeline> weekendTimeline) {
		this.weekendTimeline = weekendTimeline;
	}

	public List<Date> getNormalDays() {
		return normalDays;
	}

	public void setNormalDays(List<Date> normalDays) {
		this.normalDays = normalDays;
	}

	public List<Date> getWeekendDays() {
		return weekendDays;
	}

	public void setWeekendDays(List<Date> weekendDays) {
		this.weekendDays = weekendDays;
	}
}
